<?php

namespace App\Console\Commands\Fee;

use App\Enums\Fee\FeeEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Service\OpenShop\UserContractService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class InitFeeDate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fee:init-fee-date';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化店铺的管理费和日期';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        OpenShopSignOrderModel::query()
                              ->with('startBusinessRel', 'mainProcessRel')
                              ->where('status', SignOrderEnum::ORDER_STATUS_COMPLETE)
                              ->get()
                              ->each(function ($item) use (&$fd) {
                                  $startTime = (int)($item->startBusinessRel->startBusinessTime ?? '');

                                  // 日期
                                  $startFeeTime = self::getStartFeeTime($startTime, $item->mainProcessRel->shopId);

                                  // 金额
                                  // TODO 部分门店做特殊处理
                                  $managePrice = UserContractService::getManagementCostEveryYear($item->orderNo);

                                  // 更新
                                  OpenShopMainProcessModel::query()->where('id', $item->mainProcessId)->update([
                                      'startFeeTime' => $startFeeTime,
                                      'managePrice'  => $managePrice
                                  ]);

                                  $this->info("shopCode:{$item->shopCode} {$startFeeTime} {$managePrice}");
                              });

        // 检查为空的记录
        $imp = OpenShopSignOrderModel::query()
                                     ->with([
                                         'mainProcessRel' => function ($query) {
                                             $query->where('startFeeTime', 0);
                                         }
                                     ])
                                     ->where('status', SignOrderEnum::ORDER_STATUS_COMPLETE)
                                     ->get()
                                     ->map(function ($item) {
                                         if (!$item->mainProcessRel) {
                                             return null;
                                         }

                                         return $item->shopCode;
                                     })->filter()->implode(',');
        if ($imp) {
            $this->warn("startFeeTime为空的记录: {$imp}");
        }
    }

    /**
     * 计算管理费日期
     * @param int $startTime
     * @param int $shopId
     * @return int
     */
    public static function getStartFeeTime(int $startTime, int $shopId): int
    {
        $bookTime = 0;
        if ($startTime > 1635696000 || $startTime == 0) {
            $bookTime = OrmNewOrderRemote::getFirstBookTime($shopId)['data']['bookTime'] ?? 0;
        }

        if ($bookTime == 0 && $startTime) {
            $bookTime = $startTime;
        }

        if ($bookTime) {
            $startFeeTime = date('Ymd', $bookTime);
        } else {
            $startFeeTime = 0;
        }

        return (int)$startFeeTime;
    }
}
